
//
//  WSJObserveNewChatTool.m
//  WCN
//
//  Created by wsj2015 on 16/7/6.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WSJObserveNewChatTool.h"
#import "WCNetworkAccessManager.h"
#import "Constants.h"
#import "WSJConversion.h"
#import "XHMessage.h"
#import "CWQIMNetManager.h"
#import "EMCDDeviceManager.h"
#import "WCNNavigationController.h"
#import "cwqMessageTypesVC.h"
static NSString *lastMessageId =nil;


@interface WSJObserveNewChatTool ()

@property (nonatomic,  strong) NSTimer *timer;


@end

@implementation WSJObserveNewChatTool

HMSingletonM(ObserveTool)

- (instancetype)init{
    if (self = [super init]) {
//        
        if ([WCNetworkAccessManager sharedMg].netStatus !=0 && [[WCDefaultManager shareMg] account]) {
            [self.timer fire];
        }
        
      
       
        [self observeNetStatus];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutNot) name:UserLogoutNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNot) name:UserLoginNotification object:nil];
        
    }
    return self;
}
- (void)logoutNot{
    [self.timer invalidate];
    _timer =nil;
   
    
}
- (void)loginNot{
    if (!_timer ) {
        [self.timer fire];
    }
    
 }
- (void)observeNetStatus
{
    [[WCNetworkAccessManager sharedMg] addObserver:self forKeyPath:@"netStatus" options: NSKeyValueObservingOptionNew context:nil];
    
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if (![[WCDefaultManager shareMg]account]) {
        return;
    }
    if ([keyPath isEqualToString:@"netStatus"]) {
        NSInteger value =[change[@"new"] integerValue];

        if (value==0) {
            [self.timer invalidate];
            _timer =nil;
        }else{
            if (!_timer) {
                [self.timer fire];
            }
            
        }
        
    }
 
}
-(NSTimer *)timer{
    if (!_timer) {
//        _timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(reqestServer) userInfo:nil repeats:YES];
////
    }
    return _timer;
}
#pragma mark -请求数据
- (void)reqestServer
{
    
    
    
    NSLog(@"检测中>>>>>>>>");
    
//    lastMessageId  获取到的最后一条消息ID 没有时传0
//    toId 接收者的ID （通常自己ID）
//    toType 接收者的类型 (护士1 患者2 通常为1)
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
     params[@"lastMessageId"] =@(0);
//    [[WCDefaultManager shareMg]account].stringId
     params[@"toId"] =@(86);
     params[@"toType"] =@(1);
    
    defineWeakSelf;
    [[WCNetworkAccessManager sharedMg] POST:kOnlineMesssageGet parameters:params success:^(NSDictionary *responseObject) {
        if (responseObject[@"data"]) {
            if([responseObject[@"data"] integerValue]==1){
                [weakSelf getNewMessageLists];
            }else{
//               [weakSelf getNewMessageLists];
            }
        }
        
        
    } failure:nil netError:nil always:^{
        
    }];
    
   
}

#pragma mark -获取新消息s
- (void)getNewMessageLists{
//    toId 接收者的ID （通常患者ID）
//    toType 接收者的类型 (护士1 患者2 通常为2)
//    该方法获取到数据后 数据会修改状态
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
   
    //    [[WCDefaultManager shareMg]account].stringId
    params[@"toId"] =@(86);
    params[@"toType"] =@(1);
    
    [[WCNetworkAccessManager sharedMg] POST:kOnlineMesssageContent parameters:params success:^(NSDictionary *responseObject) {
        
//        NSMutableDictionary *wsjDict =[NSMutableDictionary dictionary];
//        
//        wsjDict[@"content"] =@"我是新文本消息";
//        wsjDict[@"id"] =@(77);
//         wsjDict[@"msgStatus"] =@(0);
//         wsjDict[@"msgType"] =@(1);
//         wsjDict[@"sendId"] =@(46);
//        wsjDict[@"sendType"] =@(2);
//         wsjDict[@"toId"] =@(473);
//         wsjDict[@"toType"] =@(1);
        
//        NSMutableArray *arr =[NSMutableArray arrayWithObject:responseObject];
        //        id = 77;
        //        msgStatus = 0;
        //        msgType = 1;
        //        sendId = 46;
        //        sendType = 2;
        //        toId = 473;
        //        toType = 1;
        
        NSArray *arr =responseObject[@"data"];
        
        LKDBHelper *db =[XHMessage getUsingLKDBHelper];


        
        [[EMCDDeviceManager sharedInstance] playNewMessageSound];
        [[EMCDDeviceManager sharedInstance] playVibration];
           [arr enumerateObjectsUsingBlock:^(NSDictionary  * dict, NSUInteger idx, BOOL * _Nonnull stop) {
        XHMessage *entity =[[XHMessage alloc] initWithDict:dict];
        
        WSJConversion * theConversion =[db searchSingle:[WSJConversion class] where:[NSString stringWithFormat:@"fromId = '%@'",entity.sender] orderBy:nil];
      
        
               UIApplicationState state = [[UIApplication sharedApplication] applicationState];
               
               switch (state) {
                   case UIApplicationStateActive:
                       [self playSoundAndVibration];
                       break;
                   case UIApplicationStateInactive:
                       [self playSoundAndVibration];
                       break;
                   case UIApplicationStateBackground:
                       [self showNotificationWithMessage:dict[@"patientAccount"][@"nickName"]];
                       break;
                   default:
                       break;
               }

        if (theConversion) {
            theConversion.unread = @([theConversion.unread integerValue] +1);
            [theConversion setDetailTextWithMediaType:entity];
            theConversion.timestamp = [NSDate date];
            entity.conversionId = theConversion.rowid;
            entity.forignKey =theConversion;
          [theConversion updateToDB];
          
          [db insertToDB:entity callback:^(BOOL result) {
              NSDictionary *userInfo =@{@"ConversionAndMessage":@[theConversion,entity]};
              [[NSNotificationCenter defaultCenter] postNotificationName:WechatNewMessageInforNotificaiton object:nil userInfo:userInfo];
              
              
            }];
        }else{
         //创建新会话
            WSJConversion *newConversion =[[WSJConversion alloc] initWithMessage:entity];
           
            newConversion.patientName =[dict[@"patientAccount"][@"nickName"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            newConversion.avatarUrl   =dict[@"patientAccount"][@"avatarFileId"];
            [db insertToDB:newConversion callback:^(BOOL result) {
                entity.conversionId =newConversion.rowid;
                entity.forignKey  =newConversion;
                [entity saveToDB];
                NSDictionary *userInfo =@{@"ConversionAndMessage":@[newConversion,entity]};
                [[NSNotificationCenter defaultCenter] postNotificationName:WechatNewMessageInforNotificaiton object:nil userInfo:userInfo];
               
               
            }];
            
           
        }
     
    }];
  
//        responseObject;
        // 文字
//        content = "\U50bb\U903c\U82cf\U795e";
//        id = 77;
//        msgStatus = 0;
//        msgType = 1;
//        sendId = 46;
//        sendType = 2;
//        toId = 473;
//        toType = 1;
        
//        图片  语音  视频
//        id = 79;
//        mediaId = "yV1_hmb1QmDnBaz-8OuTkvPcn1DagR9cDImbNj6In6hWBMU9IKwB1vyeyfXTKMyX";
//        msgStatus = 0;
//        msgType = 2;
//        sendId = 46;
//        sendType = 2;
//        toId = 473;
//        toType = 1;
       
        
    } failure:nil netError:nil always:^{
        
    }];
    
}
- (void)playSoundAndVibration{


// 收到消息时，播放音频
[[EMCDDeviceManager sharedInstance] playNewMessageSound];
// 收到消息时，震动
[[EMCDDeviceManager sharedInstance] playVibration];
}
#pragma mark -发送一条媒体消息给后台
- (void)sendAmessageToServerWithMessage:(XHMessage *)message
                                mediaId:(NSString *)mediaId
                           thumbMediaId:(NSString *)thumbMediaId
                              complelte:(void (^)(id responseObject))complelte
                                    fail:(void (^)(id errmesg))fail

{
//    sendId  发送者ID(护士ID)
//    sendType 发送者类型 (1为护士，2为患者 该接口使用 1)
//    toId 接收者ID(患者ID)
//    toType 接收者类型(该接口使用2)
//    msgType (1 text 2 image 3 voice 4 video)
//    content (msgType为1的时候使用)
//    mediaId(msgType 为2,3,4时使用)
//    thumbMediaId (msgType 为4时使用)
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    //    [[WCDefaultManager shareMg]account].stringId
    params[@"sendId"] =@(86) ;
    params[@"sendType"] =@(1);
    params[@"toId"] =@(46);
    params[@"toType"] =@(2);
    if (message.messageMediaType !=0) {
        params[@"mediaId"] =mediaId;
    }
    
    switch (message.messageMediaType) {
        case XHBubbleMessageMediaTypeText:
             params[@"msgType"] =@(1);
            params[@"content"] =message.text;
            break;
        case  XHBubbleMessageMediaTypePhoto:
            params[@"msgType"] =@(2);
          
            break;
        case  XHBubbleMessageMediaTypeVoice:
            params[@"msgType"] =@(3);
           
            break;
        case  XHBubbleMessageMediaTypeVideo:
            params[@"msgType"] =@(4);
            params[@"thumbMediaId"] =thumbMediaId;
            break;
            
        default:
            break;
    }
  
   
    
    
    [[WCNetworkAccessManager sharedMg] POST:kWechat_AddMessage parameters:params success:^(id responseObject) {
        if (complelte) {
            complelte(responseObject);
        }
        
    } failure:^(NSString *msg) {
        if (fail) {
            fail(msg);
        }
        
    } netError:^(NSString *err){
        fail(err);
        
    } always:^(){
      
    }];
    
}

- (void)showNotificationWithMessage:(NSString *)name
{
//    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
//    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
//
    notification.fireDate = [NSDate date]; //触发通知的时间
//
//    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
//        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
//        NSString *messageStr = nil;
//        switch (messageBody.messageBodyType) {
//            case eMessageBodyType_Text:
//            {
//                messageStr = ((EMTextMessageBody *)messageBody).text;
//            }
//                break;
//            case eMessageBodyType_Image:
//            {
//                messageStr = NSLocalizedString(@"message.image", @"Image");
//            }
//                break;
//            case eMessageBodyType_Location:
//            {
//                messageStr = NSLocalizedString(@"message.location", @"Location");
//            }
//                break;
//            case eMessageBodyType_Voice:
//            {
//                messageStr = NSLocalizedString(@"message.voice", @"Voice");
//            }
//                break;
//            case eMessageBodyType_Video:{
//                messageStr = NSLocalizedString(@"message.video", @"Video");
//            }
//                break;
//            default:
//                break;
//        }
//        
//        //        NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
//        //        if (message.messageType == eMessageTypeGroupChat) {
//        //            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
//        //            for (EMGroup *group in groupArray) {
//        //                if ([group.groupId isEqualToString:message.conversationChatter]) {
//        //                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
//        //                    break;
//        //                }
//        //            }
//        //        }
//        //        else if (message.messageType == eMessageTypeChatRoom)
//        //        {
//        //            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//        //            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
//        //            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
//        //            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
//        //            if (chatroomName)
//        //            {
//        //                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
//        //            }
//        //        }
//        //
//                notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
//    }
//    else{
//        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    if (name ==nil) {
          notification.alertBody = [NSString stringWithFormat:@"来自%@的新信息",name];
    }else{
         notification.alertBody =@"来自患者的新信息";
    }
  
//    }
//    
//#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
//    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
//    
//    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
//    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
//    if (timeInterval < kDefaultPlaySoundInterval) {
//        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
//    } else {
        notification.soundName = UILocalNotificationDefaultSoundName;
//        self.lastPlaySoundDate = [NSDate date];
//    }
//    
    NSDictionary *userInfo = @{@"content":name};
//    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
//    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
    notification.userInfo = userInfo;
//
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//    UIApplication *application = [UIApplication sharedApplication];
//    application.applicationIconBadgeNumber += 1;
}
- (void)dealloc{
    [self.timer invalidate];
    _timer=nil;
    [[WCNetworkAccessManager sharedMg] removeObserver:self forKeyPath:@"netStatus"];
}

+ (void)chatMessageWithApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    if (!launchOptions) {
        return;
    }
    NSDictionary *userInfor = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
    if (userInfor[@"content"]) {
        //本地通知来自前微信聊天的本地推送
        
        cwqMessageTypesVC *vc =[cwqMessageTypesVC new];
        WCNNavigationController *nav =[[UIApplication sharedApplication].delegate window].rootViewController;
        [nav pushViewController:vc animated:YES];
        
    }
 

}

@end
